﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Iacym.Entities;

namespace Iacym.Repository
{
    public class UbigeoRepository :MasterRepository, IUbigeoRepository
    {

        public List<UBIGEO> GetAllFromUbigeos()
        {
            var query = from u in context.UBIGEOs
                        select u;
            return query.ToList();
        }

        public List<UBIGEO> GetFromUbigeoByCriterio(string criterio)
        {

            var query = from u in context.UBIGEOs
                        select u;
            if (criterio!=null && criterio!=string.Empty && criterio!= "")
	        {
                query = from u in context.UBIGEOs
		                where (u.Departamento.ToUpper().Contains(criterio)||
                        u.Provincia.ToUpper().Contains(criterio)||
                        u.Distrito.ToUpper().Contains(criterio)) ||
                        u.IdUbigeo.ToUpper().Contains(criterio)
                        select u;
	        }
                        
            return query.ToList();
        }

        public UBIGEO GetFromUbigeoByUbigeo(string ubigeo)
        {
            var query = from u in context.UBIGEOs
                        where u.IdUbigeo.Equals(ubigeo)
                        select u;            
            
            return query.SingleOrDefault();

        }

        public void AddUbigeo(UBIGEO ubigeo)
        {
            context.UBIGEOs.Add(ubigeo);
            context.SaveChanges();
        }

        public void UpdateUbigeo(UBIGEO ubigeo)
        {
            context.UBIGEOs.Attach(ubigeo);
            context.Entry(ubigeo).State = System.Data.EntityState.Detached;
            context.Entry(ubigeo).State = System.Data.EntityState.Modified;
            context.SaveChanges();
        }

        public bool ExisteDuplicidad(string departamento, string provincia, string distrito, string ubigeo, int numero)
        {
            var query = from u in context.UBIGEOs
                        where u.Departamento.ToUpper().CompareTo(departamento.ToUpper()) == 0
                        && u.Provincia.ToUpper().CompareTo(provincia.ToUpper()) == 0 
                        && u.Distrito.ToUpper().CompareTo(distrito.ToUpper()) == 0
                        && u.IdUbigeo.ToUpper().CompareTo(ubigeo.ToUpper()) == 0 
                        && u.numero !=numero
                        select u;
            return query.Any();

        }


        public UBIGEO GEtFromUbigeoByNumero(int numero)
        {
            return context.UBIGEOs.Find(numero);
        }


        public void RemoveUbiegeo(int id)
        {
            var existe = context.UBIGEOs.Find(id);
            if (existe != null)
            {
                context.UBIGEOs.Remove(existe);
                context.SaveChanges();
            }
        }
    }
}
